#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL.h
#else
#include <SDL.h>
#endif
#include "sprig.h"
#include <math.h>
#include "GameObject.cpp"
#include <time.h>
#include <SDL_ttf.h>
#include <string.h>
#include <cmath>

#define SCREEN_WIDTH 1280
#define SCREEN_HEIGHT 640


#define INIT_X_P1 200
#define INIT_X_P2 1000
#define G_LVL 523
#define BULLET_MULT 30 //fire_power ranges from 1-10. actual bullet power = BULLET_MULT + (10 * (fire_power-5)/5). Ranges from [20 : 40]
#define TIME_INTERVAL 250


int main ( int argc, char** argv )
{
    int x_position = INIT_X_P1;
    int y_position = G_LVL;
    int x_position2 = INIT_X_P2;
    int y_position2 = G_LVL;
    double shoot_angle = 90.0;
    double shoot_angle2 = 90.0;
    int bullet_x, bullet_y;
    int fire_power = 5;
//    timer t; //create timer.





    // initialize SDL video
    if ( ( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }



    //TTF_Init() before using SDL_ttf functions
    if ( TTF_Init() == -1)
        return 1;

    // make sure SDL, TTF clean up before exit
    atexit(SDL_Quit);
    atexit(TTF_Quit);

    // create a new window
    SDL_Surface* screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 16,
                                           SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }


    //set up all images
    SDL_Surface* tank = SDL_LoadBMP("tank_cartoon_green.bmp");
    SDL_Surface* tank2 = SDL_LoadBMP("tank_cartoon_green.bmp");
    SDL_Surface* shooter = SDL_LoadBMP("tank_cartoon_green_shooter.bmp");
    SDL_Surface* title = NULL;
    SDL_Surface* p1 = NULL;
    SDL_Surface* p2 = NULL;
    SDL_Surface* health1 = NULL;
    SDL_Surface* health2 = NULL;
    SDL_Surface* health_num1 = NULL;
    SDL_Surface* health_num2 = NULL;
    SDL_Surface* background = NULL;
    SDL_Surface* bullet = NULL;
    SDL_Surface* p1win = NULL;
    SDL_Surface* p2win = NULL;
    SDL_Surface* power = NULL;
    SDL_Surface* movesSurface = NULL;
 //   SDL_Surface* testingsurface = NULL; //For testing

    //The font that's going to be used
    TTF_Font *title_font = TTF_OpenFont( "Lazy.ttf", 72 );
    TTF_Font *turn_font = TTF_OpenFont("Lazy.ttf", 32);
    TTF_Font *health_font = TTF_OpenFont("Lazy.ttf", 28);
    TTF_Font *power_steps_font = TTF_OpenFont("Lazy.ttf", 24);

    //load background image
    background = SDL_LoadBMP( "space.bmp" );
    bullet = SDL_LoadBMP( "trollface.bmp");
    p1win = SDL_LoadBMP("notbadp1.bmp");
    p2win = SDL_LoadBMP("notbadp2.bmp");



    //The color of the font
    SDL_Color white = { 255, 255, 255 };
    SDL_Color red = {255, 0, 0};
    SDL_Color blue = {0, 0, 255};
    SDL_Color spring_green = {0,255,127};
    SDL_Color gold = {255, 215, 0};


    //create instances of Tank, Bullet class
    Tank t, t2;
    Bullet b;

    //set all healths to 100
    t.set_health();
    t2.set_health();
    b.set_health();

    char power_text[100] = {0};
    snprintf(power_text, 99, "Fire Power: %d / 10", fire_power);


    //text to be the health displayed at the top
    char health_text[100] = {0};
    char testing[100] = {0}; //FOR TESTING
    snprintf(health_text, 99, "P1 health : %d", t.health);
//    snprintf(testing, 99, "T1X = %d", t.x);
       //If there was a problem in loading the background
   if( background == NULL ) return 2;
   if (bullet == NULL) return 1;
   if( p1win == NULL || p2win == NULL)
    {
        return 3;
    }


       //Render all of the text
    title = TTF_RenderText_Solid( title_font, "MOON TANKS", white );
    p1 = TTF_RenderText_Solid( turn_font, "P1's turn", red );
    p2 = TTF_RenderText_Solid( turn_font, "P2's turn", blue );


    if (title == NULL) return 1;



    if (!tank  || !shooter)
    {
        printf("Unable to load bitmap: %s\n", SDL_GetError());
        return 1;
    }

    //gets rid of extra black pixels, makes them trasnparent
    //so that we can layer images
    SDL_SetColorKey(tank,SDL_SRCCOLORKEY,SDL_MapRGB(tank->format,0,0,0));
    SDL_SetColorKey(tank2,SDL_SRCCOLORKEY,SDL_MapRGB(tank->format,0,0,0));
    SDL_SetColorKey(shooter,SDL_SRCCOLORKEY,SDL_MapRGB(shooter->format,0,0,0));
  //  if (b.health > 0)
      //  SDL_SetColorKey(bullet,SDL_SRCCOLORKEY,SDL_MapRGB(bullet->format,0,0,0));


    SDL_Surface* shooterRotated = SPG_Rotate(shooter, 360-shoot_angle, 0);
    SDL_Surface* shooterRotated2 = SPG_Rotate(shooter, 360-shoot_angle2, 0);


    SDL_SetColorKey(shooterRotated,SDL_SRCCOLORKEY,SDL_MapRGB(shooterRotated->format,0,0,0));
    SDL_SetColorKey(shooterRotated2,SDL_SRCCOLORKEY,SDL_MapRGB(shooterRotated2->format,0,0,0));
/*
//creates the rectangle holding the image
    SDL_Rect dstrect;
    dstrect.x = x_position;
    dstrect.y = y_position;

    SDL_Rect dstrect2;
    dstrect2.x =  x_position+16+(2*(shooter->w)/5) * cos(shoot_angle*0.0174532925);
    dstrect2.y = y_position-10 - (2*(shooter->w)/5) * sin(shoot_angle*0.0174532925);
*/

    //rotation



//    dstrect.x = (screen->w - bmp->w) / 2;
//    dstrect.y = (screen->h - bmp->h) / 2;

    // program main loop
    bool done = false;
    bool paused = false;
    bool p1_turn = true; //TRUE = P1 turn
    bool p2_turn = false;
    bool fired = false;//Once player who's turn it is has fired, fired becomes true --> turn flips
    int p1_orig = x_position;//the x position the players when their turns start
    int p2_orig = x_position2;//the x position the players when their turns start
    int moves = 0;
    int winner;
    double bullet_power = 30.0;
    int movesLeft = 3;


    //while game is going
    while (!done)
    {
if(!paused){
        if (fired) SDL_Delay(50);

        bullet_power = BULLET_MULT + (10 * ((double)fire_power-5)/5); //will range from 6 - 60

        //pring the firepower value
        sprintf(power_text, "Fire Power: %d / 10", fire_power);
        power = TTF_RenderText_Solid(power_steps_font, power_text, gold);

        char moves_left[100] = {0};
        snprintf(moves_left, 99, "Moves Left: %d / 3", movesLeft);
        movesSurface = TTF_RenderText_Solid(power_steps_font, moves_left, gold);

        //decrement bullet's y velocity with each iteration of the loop to simulate gravity
        b.velocity_y += 1;

        //update tank class coordinates
        t.update(x_position, y_position, 30, 30, 0, 0, 5, 0, tank);
        t2.update(x_position2, y_position2, 30, 30, 0, 0, 5, 0, tank2);

        sprintf(health_text, "P1 health : %d", t.health);
        health1 = TTF_RenderText_Solid( health_font, health_text, spring_green );

        sprintf(health_text, "P2 health : %d", t2.health);
        health2 = TTF_RenderText_Solid( health_font, health_text,  spring_green );

    //sprintf(testing, "T1X = %d  T1XW = %d  T1Y = %d   T1YH = %d  BX = %d  BY = %d", t2.x-25, t2.x + t2.width + 75, t2.y -23, t2.y + t2.height+7, bullet_x, bullet_y);
    //testingsurface = TTF_RenderText_Solid(health_font, testing, spring_green);
            //end game when a tank dies
        if (t.health <= 0){//if p1 = dead
            winner = 2;//p2 wins
            done = true;//exit loop

        }
        if (t2.health <= 0){//if p2 = dead
            winner = 1;//p1 wins
            done = true;//exit loop
        }

        if (bullet_x < 0 || bullet_x > SCREEN_WIDTH || bullet_y > G_LVL + t.height) //bullets disappear once they hit the ground. bullets are allowed to go up and above screen
            fired = false;//set bullet Surface to NULL if it is out of the bounds

        if (fired){//if bullet exists: 1) check for collisions 2) accelerate it

            if (b.intersects(t,bullet_x,bullet_y) && p1_turn){
                t.health -= 20;
                fired = false;
            }
            else if (b.intersects(t2, bullet_x,bullet_y ) && p2_turn){
                t2.health -= 20;
                fired = false;
            }
            else {//no intersections --> just accelerate

                bullet_x += b.velocity_x;
                bullet_y += b.velocity_y;
            }
        }
}
       // b.accelerate();
       // b.set_velocity_y(10);

        // message processing loop
        SDL_Event event;
        while (SDL_PollEvent(&event))
        {
            // check for messages
            switch (event.type)
            {
                // exit if the window is closed
            case SDL_QUIT:
                done = true;
                break;

                // check for keypresses
            case SDL_KEYDOWN:
                {
                    // exit if ESCAPE is pressed
                    if (event.key.keysym.sym == SDLK_ESCAPE){
                        done = true;
                    }
                    if (event.key.keysym.sym == SDLK_p){


                    paused = !paused ;

                    }

                    if (p1_turn && !fired){//P1 TURN
                        if (event.key.keysym.sym == SDLK_a){
                            if(movesLeft>0){
                            x_position -= t.velocity_x;
                            movesLeft = movesLeft - 1;}}
                        if (event.key.keysym.sym == SDLK_d){
                            if(movesLeft>0){
                            x_position += t.velocity_x;
                            movesLeft = movesLeft - 1;}}
                        if (event.key.keysym.sym == SDLK_w && shoot_angle <= 85){
                            shoot_angle += 5;}
                        if (event.key.keysym.sym == SDLK_s && shoot_angle >= 10){
                            shoot_angle -= 5;}
                        if (event.key.keysym.sym == SDLK_y && fire_power < 10){
                            fire_power++;}
                        if (event.key.keysym.sym == SDLK_h && fire_power > 1){
                            fire_power--;}
                        if (event.key.keysym.sym == SDLK_z){//T1 FIRE BULLET
                            b.update(x_position+16+(2*(shooter->w)/5) * +3*cos(shoot_angle*0.0174532925) ,
                                     y_position-10 - (2*(shooter->w)/5) * sin(shoot_angle*0.0174532925),
                                     16, 16, 0, 0, (bullet_power * cos(shoot_angle*0.0174532925)),
                                     -1*bullet_power * sin(shoot_angle*0.0174532925), bullet);
                            bullet_x = b.x;
                            bullet_y = b.y;
                            p2_turn = true;
                            p1_turn = false;
                            fired = true;
                            movesLeft = 3;
                        }
                    }
                    else if (p2_turn && !fired){//P2 TURN
                        if (event.key.keysym.sym == SDLK_LEFT){
                            if(movesLeft>0){
                            x_position2 -= t2.velocity_x;
                            movesLeft = movesLeft - 1;}}
                        if (event.key.keysym.sym == SDLK_RIGHT){
                            if(movesLeft>0){
                            x_position2 += t2.velocity_x;
                            movesLeft = movesLeft - 1;}}
                        if (event.key.keysym.sym == SDLK_UP && shoot_angle2 >= 95){
                            shoot_angle2 -= 5;}
                        if (event.key.keysym.sym == SDLK_DOWN && shoot_angle2 <= 170){
                            shoot_angle2 += 5;}
                        if (event.key.keysym.sym == SDLK_y && fire_power < 10){
                            fire_power++;}
                        if (event.key.keysym.sym == SDLK_h && fire_power > 1){
                            fire_power--;}
                        if (event.key.keysym.sym == SDLK_SLASH){//T2 FIRE BULLET
                            b.update(x_position2+16+(2*(shooter->w)/5) * cos(shoot_angle2*0.0174532925),
                                     y_position2-10 - (2*(shooter->w)/5) * sin(shoot_angle2*0.0174532925),
                                     20, 20, 0, 0, (bullet_power * cos(shoot_angle2*0.0174532925)),
                                     -1*bullet_power * sin(shoot_angle2*0.0174532925), bullet);
                            bullet_x = b.x;
                            bullet_y = b.y;
                            p2_turn = false;
                            p1_turn = true;
                            fired = true;
                            movesLeft = 3;
                        }
                    }

                }//end SDL_KEYDOWN
            } // end switch event type
        } // end of event processing

        //if (b.intersects(t) || b.intersects(t2))//if b exists and it hits a tank
            //b.destroy

        //if tanks have health < 0, sets it to 0 (for display)
        t.fix_health();
        t2.fix_health();

            // DRAWING STARTS HERE
        SDL_Surface* shooterRotated = SPG_Rotate(shooter, 360-shoot_angle, 0);
        SDL_Surface* shooterRotated2 = SPG_Rotate(shooter, 360-shoot_angle2, 0);


        SDL_SetColorKey(shooterRotated,SDL_SRCCOLORKEY,SDL_MapRGB(shooterRotated->format,0,0,0));
        SDL_SetColorKey(shooterRotated2,SDL_SRCCOLORKEY,SDL_MapRGB(shooterRotated2->format,0,0,0));


        SDL_Rect dstrect;
        SDL_Rect dstrect2;
        dstrect.x = x_position;
        dstrect.y = y_position;
        dstrect2.x =  x_position+16+(2*(shooter->w)/5) * cos(shoot_angle*0.0174532925);//for cannon
        dstrect2.y = y_position-10 - (2*(shooter->w)/5) * sin(shoot_angle*0.0174532925);

        SDL_Rect dstrect3, dstrect4;
        dstrect3.x = x_position2;
        dstrect3.y = y_position2;
        dstrect4.x =  x_position2+16+(2*(shooter->w)/5) * cos(shoot_angle2*0.0174532925);
        dstrect4.y = y_position2-10 - (2*(shooter->w)/5) * sin(shoot_angle2*0.0174532925);

        SDL_Rect title_rect;
        title_rect.x = SCREEN_WIDTH / 2 - title_rect.w / 2;
        title_rect.y = 0;


        SDL_Rect turn_rect;
        turn_rect.x = SCREEN_WIDTH / 2 - turn_rect.w / 2;
        turn_rect.y = title_rect.h + 10;

        SDL_Rect pow_rect;
        pow_rect.x = SCREEN_WIDTH / 2 - pow_rect.w / 2;
        pow_rect.y = turn_rect.y + turn_rect.h + 10;

        SDL_Rect moves_rect;
        moves_rect.x = SCREEN_WIDTH / 2 - moves_rect.w / 2;
        moves_rect.y = pow_rect.y + pow_rect.h + 10;

        SDL_Rect background_rect;
        background_rect.x = 0;
        background_rect.y = 0;
        background_rect.w = SCREEN_WIDTH;
        background_rect.h = SCREEN_HEIGHT;

        SDL_Rect h1_rect, h2_rect, h1_num, h2_num;
        h1_rect.x = INIT_X_P1;
        h1_rect.y = title_rect.y + turn_rect.h + 10;
        h2_rect.x = INIT_X_P2 + dstrect.w - h2_rect.w;
        h2_rect.y = title_rect.y + turn_rect.h + 10;
        h1_num.x = h1_rect.x + (h1_rect.w / 2) - (h1_num.w / 2);
        h1_num.y = h1_rect.y + h1_rect.h + 10;


//FOR TESTING PURPOSES
  /*      SDL_Rect testing_rect;
        testing_rect.x = 300;
        testing_rect.y = 300;*/

            // clear screan
        SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));

            // draw bitmaps
        SDL_BlitSurface(background, 0, screen, &background_rect);
        SDL_BlitSurface(shooterRotated, 0, screen, &dstrect2);
        SDL_BlitSurface(tank, 0, screen, &dstrect);
        SDL_BlitSurface(shooterRotated2, 0, screen, &dstrect4);
        SDL_BlitSurface(tank2, 0, screen, &dstrect3);
        SDL_BlitSurface(title, 0, screen, &title_rect);
        SDL_BlitSurface(health1, 0, screen, &h1_rect);
        SDL_BlitSurface(health2, 0, screen, &h2_rect);
        SDL_BlitSurface(health_num1, 0, screen, &h1_num);
        SDL_BlitSurface(power, 0, screen, &pow_rect);
        SDL_BlitSurface(movesSurface, 0, screen, &moves_rect);
//        SDL_BlitSurface(testingsurface, 0, screen, &testing_rect);

        //create bullet
        if (fired){
            SDL_SetColorKey(bullet,SDL_SRCCOLORKEY,SDL_MapRGB(bullet->format,0,0,0));
            SDL_Rect bull;
            bull.x = bullet_x;
            bull.y = bullet_y;
            SDL_BlitSurface(bullet, 0, screen, &bull);
        }



        //display whose turn it is
        if (p1_turn)
            SDL_BlitSurface(p1, 0, screen, &turn_rect);
        if (p2_turn)
            SDL_BlitSurface(p2, 0, screen, &turn_rect);

               // if (b.health > 0)
           // SDL_BlitSurface(bullet, 0, screen, &dstrect);

        //if (b.health > 0)
            //SDL_BlitSurface(bullet, 0, screen, &dstrect3);





        // DRAWING ENDS HERE

        // finally, update the screen :)
        SDL_Flip(screen);
    } // end main while loop


    //DO FUN STUFF TO SHOW WHO WON
    if (winner == 1){
        SDL_Rect winnerrect;
        winnerrect.x = SCREEN_WIDTH / 2 - p2win->w / 2;
        winnerrect.y = SCREEN_HEIGHT / 2 - p2win->h / 2;
        SDL_BlitSurface(p1win, 0, screen, &winnerrect);
        SDL_Flip(screen);
        SDL_Delay(20000);
    }
    if (winner == 2){

        SDL_Rect winnerrect;
        winnerrect.x = SCREEN_WIDTH / 2 - p2win->w / 2;
        winnerrect.y = SCREEN_HEIGHT / 2 - p2win->h / 2;
        SDL_BlitSurface(p2win, 0, screen, &winnerrect);
        SDL_Flip(screen);
        SDL_Delay(20000);
    }

    // free loaded bitmap
    if (p1win != NULL) SDL_FreeSurface(p1win);
    if (p2win != NULL) SDL_FreeSurface(p2win);
    SDL_FreeSurface(tank);
    SDL_FreeSurface(tank2);
    SDL_FreeSurface(shooterRotated);
    SDL_FreeSurface(shooterRotated2);
    SDL_FreeSurface( background );
    SDL_FreeSurface( title );
    SDL_FreeSurface( p1 );
    SDL_FreeSurface( p2 );
    SDL_FreeSurface( bullet);

    // all is well ;)
    printf("Exited cleanly\n");
    return 0;

}


